import urllib,urllib.request
import socket
import urllib.error

url = "http://httpbin.org/post"
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"}
try:

    response = urllib.request.urlopen("http://www.baidu.com",timeout=0.1)
except urllib.error.URLError as e:
    if isinstance(e.reason,socket.timeout):
        print('TIME OUT')
#post方式
data = bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf8')
req = urllib.request.Request(url=url,data=data,headers=headers,method='POST')
response = urllib.request.urlopen('http://httpbin.org/post',data=data)
print(response.read())

#handler 代理
# proxy_handler = urllib.request.ProxyHandler({
#     'http':'http://127.0.0.1:9743',
#     'https':'https://127.0.0.19743'
# })
# opener = urllib.request.build_opener(proxy_handler)
# response = opener.open('http://www.baidu.com')
# print(response.read())

#cookie
import http.cookiejar
cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
for item in cookie:
    print(item.name+"="+item.value)

#cookie   MozillaCookieJar
import http.cookiejar
filename = 'cookie.txt'
cookie = http.cookiejar.MozillaCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True,ignore_expires=True)

#cookie LWPCookieJar
import http.cookiejar
filename = 'cookie.txt'
cookie = http.cookiejar.LWPCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True,ignore_expires=True)

